<?php
/**
 * 系统缓存类
 */
defined('IN_IXDCW') or exit('Access Denied');

require_once DT_INC.'/post.func.php';
require_once DT_ROOT.'/admin/global.func.php';

/**
 * 系统缓存操作类/项目缓存操作类
 * 将cache_* 函数独立到这个类中
 * Class PCache
 */
class PCache {

	const CACHE_TYPE_DIR = 'dir';

	const AUTO_CATEGORY_RANK = 'autoCategoryRank.php';

	const AUTO_CATEGORY_RANK_TREE = 'autoCategoryRankTree.php';
	/**
	 * 删除项目缓存文件
	 * @param        $str   含有这个字串的文件
	 * @param string $type  类型 dir 为目录
	 * @param string $dir
	 */
	public static function clear($str, $type = '', $dir = '') {
		$dir   = $dir ? DT_CACHE . '/' . $dir . '/' : DT_CACHE . '/';
		$files = glob($dir . '*');
		if (is_array($files)) {
			if ($type == self::CACHE_TYPE_DIR) {
				foreach ($files as $file) {
					if (is_dir($file)) {
						File::dirDelete($file);
					} else {
						if (File::ext($file) == $str) File::del($file);
					}
				}
			} else {
				foreach ($files as $file) {
					if (!is_dir($file) && strpos(basename($file), $str) !== false) File::del($file);
				}
			}
		}
	}

	/**
	 * 删除全部项目缓存文件
	 * @param string $dir
	 * @return bool
	 */
	public static function clearAll($dir = '') {
		$dir   = $dir ? DT_CACHE . '/' . $dir . '/' : DT_CACHE . '/';
		$files = glob($dir . '*.php');
		if (is_array($files)) {
				foreach ($files as $file) {
					if (!is_dir($file)) File::del($file);
				}
			}
		return true;
	}

	/**
	 * 写入缓存
	 * @param        $file      文件名称
	 * @param        $string    数据名称
	 * @param string $dir       文件路径
	 * @return bool|int
	 */
	public static function write($file, $string, $dir = '') {
		if (is_array($string)) $string = "<?php defined('IN_IXDCW') or exit('Access Denied'); return " . Str::trimSpace(var_export($string, true)) . "; ?>";
		$file = $dir ? DT_CACHE . '/' . $dir . '/' . $file : DT_CACHE . '/' . $file;
		if (!file_exists(dirname($file))) {
			File::dirCreate(dirname($file));
		}
		$strlen = File::put($file, $string);
		return $strlen;
	}

	/**
	 * 删除文件缓存
	 * @param        $file
	 * @param string $dir
	 * @return bool
	 */
	public static function delete($file, $dir = '') {
		$file = $dir ? DT_CACHE . '/' . $dir . '/' . $file : DT_CACHE . '/' . $file;
		return File::del($file);
	}

	/**
	 * 获得缓存文件内容
	 * @param        $file
	 * @param string $dir
	 * @param string $mode
	 * @return array|mixed|string
	 */
	public static function read($file, $dir = '', $mode = '') {
		global $_userid;
		static $_cache = array();
		$key = $dir.'.'.$file;
		if (isset($_cache[$key])) {
			return $_cache[$key];
		} else {
			$file = $dir ? DT_CACHE . '/' . $dir . '/' . $file : DT_CACHE . '/' . $file;
			if (!is_file($file)) {//如果缓存不存在，则创建缓存
				$filename =  basename($file);
				if($filename == 'autoCategoryRank.php'){
					self::sysAutoRank();
					$_cache[$key] = $mode ? File::get($file) : include $file;
					return $_cache[$key] ? $_cache[$key] : array();
				}
				if(strpos($filename,'fields-auto') !== false ){
					self::sysAutoFields();
					$_cache[$key] = $mode ? File::get($file) : include $file;
					return $_cache[$key] ? $_cache[$key] : array();
				}
				$cache_fun = 'sys'.ucwords(preg_replace('/([-_][a-z1-9_]*)?.php/i','',$filename));
				if($cache_fun == 'sysCatetree') $cache_fun = 'sysCategory';
				if(is_callable(array('self',$cache_fun))){//如果方法存在并可以被调用
					if($cache_fun == 'sysAutoCategory'){
						$autoTypes = AutoCategory::getTypes();
						$autoTypeKeys = array_keys($autoTypes);
						foreach($autoTypeKeys as $v){
							self::$cache_fun($v);
						}
						$_cache[$key] = $mode ? File::get($file) : include $file;
						return $_cache[$key] ? $_cache[$key] : array();
					}elseif($cache_fun == 'sysRight' or $cache_fun == 'sysMenu'){
						self::$cache_fun($_userid);
						$_cache[$key] = $mode ? File::get($file) : include $file;
						return $_cache[$key] ? $_cache[$key] : array();
					}else{
						self::$cache_fun();
						$_cache[$key] = $mode ? File::get($file) : include $file;
						return $_cache[$key] ? $_cache[$key] : array();
					}
				}else{
					$_cache[$key] = array();
				}
			} else {
				$_cache[$key] = $mode ? File::get($file) : include $file;
			}
			return $_cache[$key];
		}
	}


	/**
	 * 输入项目id 创建模块设置缓存 module-$id.php
	 * 未输入模块id, 则更新所有模块信息
	 * @var int $moduleid 模块id
	 * @return boolean
	 */
	public static function sysModule($moduleid = 0) {
		global $db;
		$table = Table::name(Table::NAME_MODULE);
		if ($moduleid) {
			// moduleinfo
			$r = $db->getOne("SELECT * FROM {$table} WHERE disabled=0 AND moduleid='$moduleid'");

			/** @var 获取setting数据库内的 初始数据 */
			$setting = get_setting($moduleid);

			if (isset($setting['seo_title_index'])) $setting['title_index'] = seo_title($setting['seo_title_index']);
			if (isset($setting['seo_title_list'])) $setting['title_list'] = seo_title($setting['seo_title_list']);
			if (isset($setting['seo_title_show'])) $setting['title_show'] = seo_title($setting['seo_title_show']);
			if (isset($setting['seo_title_search'])) $setting['title_search'] = seo_title($setting['seo_title_search']);
			if (isset($setting['seo_keywords_index'])) $setting['keywords_index'] = seo_title($setting['seo_keywords_index']);
			if (isset($setting['seo_keywords_list'])) $setting['keywords_list'] = seo_title($setting['seo_keywords_list']);
			if (isset($setting['seo_keywords_show'])) $setting['keywords_show'] = seo_title($setting['seo_keywords_show']);
			if (isset($setting['seo_keywords_search'])) $setting['keywords_search'] = seo_title($setting['seo_keywords_search']);
			if (isset($setting['seo_description_index'])) $setting['description_index'] = seo_title($setting['seo_description_index']);
			if (isset($setting['seo_description_list'])) $setting['description_list'] = seo_title($setting['seo_description_list']);
			if (isset($setting['seo_description_show'])) $setting['description_show'] = seo_title($setting['seo_description_show']);
			if (isset($setting['seo_description_search'])) $setting['description_search'] = seo_title($setting['seo_description_search']);

			$setting['moduleid']      = $moduleid;
			$setting['name']          = $r['name'];
			$setting['moduledir']     = $r['moduledir'];
			$setting['module']        = $r['module'];
			$setting['ismenu']        = $r['ismenu'];
			$setting['isrewrite']     = $r['isrewrite'];
			$setting['domain']        = $r['domain'];
			$setting['linkurl']       = $r['linkurl'];
			$setting['isfront']       = $r['isfront'];
			$setting['ismember']      = $r['ismember'];
			$setting['issubscribe']   = $r['issubscribe'];
			$setting['isupdate']      = $r['isupdate'];
			$setting['isuserupgrade'] = $r['isuserupgrade'];
			$setting['cat']           = $r['cat'];


			self::write('module-' . $moduleid . '.php', $setting);

			if (isset($setting['split'])) {
				if ($setting['split']) {
					self::write($moduleid . '.part', $moduleid);
				} else {
					self::delete($moduleid . '.part');
				}
			}
			return true;
		} else {
			$result  = $db->query("SELECT moduleid, module, name,moduledir,domain,linkurl,style,listorder,isrewrite,islink,ismenu,isupdate,isblank,isfront,issubscribe,isuserupgrade,ismember,cat,logo FROM {$db->getPre()}module WHERE disabled=0 ORDER by listorder asc,moduleid desc");
			$CACHE   = array();
			$modules = array();
			while ($r = $db->fetchArray($result)) {
				if (!$r['islink']) {
					$linkurl = $r['domain'] ? $r['domain'] : linkurl($r['moduledir'] . '/', 1);
					if ($r['moduleid'] == 1) $linkurl = SITE_URL;
					if ($linkurl != $r['linkurl']) {
						$r['linkurl'] = $linkurl;
						$db->query("UPDATE {$table} SET linkurl='$linkurl' WHERE moduleid='$r[moduleid]' ");
					}
					self::sysModule($r['moduleid']);
				}
				$modules[$r['moduleid']] = $r;
			}
			$CACHE['module'] = $modules;
			$CACHE['dt']     = self::read('module-1.php');
			self::write('module.php', $CACHE);
		}
	}


	/**
	 * 清空缓存的tag标记,则相当于更新了一遍, 需要时候按照最新的生成
	 * @param bool $all
	 */
	public static function sysClearTag($all = false) {
		global $DT_TIME;
		$globs = glob(DT_CACHE . '/tag/*.htm');
		if ($globs) {
			foreach ($globs as $v) {
				if ($all) {
					File::del($v);
				} else {
					$exptime = intval(substr(File::get($v), 4, 14));
					if ($exptime && $DT_TIME > $exptime) File::del($v);
				}
			}
		}
	}

	/**
	 * 创建分类缓存数据category-$id.php
	 * @param int   $moduleid
	 * @param array $data
	 */
	public static function sysCategory($moduleid = 0, $data = array()) {
		global $db, $MODULE;
		$table = Table::name(Table::NAME_CATEGORY);
		if ($moduleid) {
			if (!$data) {
				$result = $db->query("SELECT * FROM {$table} WHERE moduleid='$moduleid' ORDER BY listorder,catid");
				while ($r = $db->fetchArray($result)) {
					$data[$r['catid']] = $r;
				}
			}
			$mod = self::read('module-' . $moduleid . '.php');
			$a   = array();
			$d   = array('listorder', 'moduleid', 'item', 'template', 'show_template', 'seo_title', 'seo_keywords', 'seo_description', 'group_list', 'group_show', 'group_add');
			foreach ($data as $r) {
				$e = $r['catid'];
				foreach ($d as $_d) {
					unset($r[$_d]);
				}
				$a[$e] = $r;
			};
			self::write('category-' . $moduleid . '.php', $a);
			if (count($data) < 200) {
				$categorys = array();
				foreach ($data as $id => $cat) {
					$categorys[$id] = array('id' => $id, 'parentid' => $cat['parentid'], 'name' => $cat['catname']);
				}
				$tree    = new tree($categorys);
				$content = $tree->get_tree(0, "<option value=\\\"\$id\\\">\$spacer\$name</option>");
				self::write('catetree-' . $moduleid . '.php', $content);
			} else {
				self::delete('catetree-' . $moduleid . '.php');
			}
		} else {
			foreach ($MODULE as $moduleid => $module) {
				self::sysCategory($moduleid);
			}
		}
	}


	/**
	 * 更新汽车分级缓存和树文件
	 * @param       $typename
	 * @param array $data
	 */
	public static function sysAutoCategory($typename, $data = array()) {
		global $db;
		$rankCacheFile = "autoCategory-{$typename}.php";
		$rankTreeFile  = "autoCategoryTree-{$typename}.php";
		$table = Table::name(Table::NAME_AUTO_CATEGORY);
		if (!$data) {
			$result = $db->query("SELECT * FROM {$table} WHERE typename='{$typename}' ORDER BY listorder,letter");
			while ($r = $db->fetchArray($result)) {
				$data[$r['arid']] = $r;
			}
			if ($typename == AutoCategory::TYPE_RANK) {
				foreach($data as $k => $v) {
					if ($v['level']>1) {
						unset($data[$k]);
					}
				}
			}
		}
		$a   = array();
		$d   = array('listorder', 'item');
		foreach ($data as $r) {
			$e = $r['arid'];
			foreach ($d as $_d) {
				unset($r[$_d]);
			}
			$a[$e] = $r;
		};
		self::write($rankCacheFile, $a);
		if (count($data) < 9000) {
			$ranks = array();
			foreach ($data as $id => $cat) {
				$ranks[$id] = array('id' => $id, 'parentid' => $cat['parentid'], 'name' => $cat['name']);
			}
			$tree    = new tree($ranks);
			$content = $tree->get_tree(0, "<option value=\\\"\$id\\\">\$spacer\$name</option>") . '</select>';
			self::write($rankTreeFile, $content);
		} else {
			self::delete($rankCacheFile);
		}
	}

	/**
	 * 生成品牌车系json缓存
	 */
	public static function sysAutoJson() {
		global $db;
		//获取品牌
		$RANK   = AutoCategory::getCache(AutoCategory::TYPE_RANK);
		$brands  = Auto::brands($RANK);
		$BRANDS = array();
		foreach ($brands as $bid => $_brand) {
			if($_brand['letter']){
				$BRANDS[$_brand['letter']][$bid] = $_brand;
			}
		}
		//获取车系
		$m=$db->query('SELECT arid,name FROM xd_auto_category WHERE level=2');
		while($results = $db->fetchArray($m)){
			$mo[$results['arid']]=$results['name'];
		}
		//生成数组
		foreach($BRANDS as $k=>$b){
			foreach($b as $v){
				$brand["'".$v['arid']."'"]['name']=$v['letter'].'.&nbsp;'.$v['name'];
				$model=explode(',',$v['arrchildid']);
				foreach($model as $mk=>$mv){
					if($mo[$mv]){
						$brand["'".$v['arid']."'"]['model'][$mv]['name']=$mo[$mv];
					}
				}
				$brand["'".$v['arid']."'"]['len']=count($brand["'".$v['arid']."'"]['model']);
			}
		}

		$brand['len'] = count($brand);
		self::write('autoJson.php', $brand);
	}
	/**
	 * 更新汽车分级缓存和树文件
	 */
	public static function sysAutoRank() {
		global $db;
		$rankCacheFile = "autoCategoryRank.php";
		$table = Table::name(Table::NAME_AUTO_CATEGORY);
		$result = $db->query("SELECT * FROM {$table} WHERE typename='rank' ORDER BY listorder,letter");
		while ($r = $db->fetchArray($result)) {
			$data[$r['arid']] = $r;
		}
		$a   = array();
		$d   = array('listorder', 'item');
		foreach ($data as $r) {
			$e = $r['arid'];
			foreach ($d as $_d) {
				unset($r[$_d]);
			}
			$a[$e] = $r;
		};
		self::write($rankCacheFile, $a);
	}
	/**
	 * 缓存地区
	 */
	public static function sysArea() {
		global $db;
		$table  = Table::name(Table::NAME_AREA);
		$data   = array();
		$result = $db->query("SELECT areaid,areaname,parentid,arrparentid,child,arrchildid,single,fullcode FROM {$table} ORDER BY listorder,areaid");
		while ($r = $db->fetchArray($result)) {
			$areaid        = $r['areaid'];
			$data[$areaid] = $r;
		}
		self::write('area.php', $data);
	}


	/**
	 * 缓存字段
	 * @param string $tb
	 */
	public static function sysFields($tb = '') {
		global $db;
		$table = Table::name(Table::NAME_FIELDS);
		if ($tb) {
			$data   = array();
			$result = $db->query("SELECT * FROM {$table} WHERE tb='$tb' ORDER BY listorder,itemid");
			while ($r = $db->fetchArray($result)) {
				$data[$r['itemid']] = $r;
			}
			self::write('fields-' . $tb . '.php', $data);
		} else {
			$tbs    = array();
			$result = $db->query("SELECT * FROM {$table}");
			while ($r = $db->fetchArray($result)) {
				if (isset($tbs[$r['tb']])) continue;
				self::sysFields($r['tb']);
				$tbs[$r['tb']] = $r['tb'];
			}
		}
	}

	/**
	 * 缓存车型库字段
	 * @param string $tb
	 */
	public static function sysAutoFields($tb = '') {
		global $db;
		$table = Table::name(Table::NAME_AUTO_FIELDS);
		if ($tb) {
			$data   = array();
			$result = $db->query("SELECT * FROM {$table} WHERE tb='$tb' ORDER BY listorder,itemid");
			while ($r = $db->fetchArray($result)) {
				$data[$r['itemid']] = $r;
			}
			self::write('fields-' . $tb . '.php', $data);
		} else {
			$tbs    = array();
			$result = $db->query("SELECT * FROM {$table}");
			while ($r = $db->fetchArray($result)) {
				if (isset($tbs[$r['tb']])) continue;
				self::sysAutoFields($r['tb']);
				$tbs[$r['tb']] = $r['tb'];
			}
		}
	}

	/**
	 * 缓存行情商品
	 */
	public static function sysQuoteProduct() {
		global $db;
		$table  = Table::name(Table::NAME_QUOTE_PRODUCT);
		$data   = array();
		$result = $db->query("SELECT pid,title,catid FROM {$table} ORDER BY listorder DESC,pid DESC");
		while ($r = $db->fetchArray($result)) {
			$data[$r['pid']] = $r;
		}
		self::write('quote_product.php', $data);
	}

	/**
	 * 清空缓存的广告
	 * @param bool $all
	 */
	public static function sysClearAd($all = false) {
		global $DT_TIME;
		$globs = glob(DT_CACHE . '/htm/*.htm');
		if ($globs) {
			foreach ($globs as $v) {
				if (strpos(basename($v), 'ad_') === false) continue;
				if ($all) {
					File::del($v);
				} else {
					$exptime = intval(substr(File::get($v), 4, 14));
					if ($exptime && $DT_TIME > $exptime) File::del($v);
				}
			}
		}
	}

	/**
	 * 生成jsconfig配置文件
	 */
	public static function sysJs() {
		global $MODULE, $CFG, $EXT;
		$data = '';
		$data .= 'var DTPath = "' . SITE_URL . '";';
		$data .= 'var SKPath = "' . DT_SKIN . '";';
		$data .= 'var EXPath = "' . $MODULE[3]['linkurl'] . '";';
		$data .= 'var CKDomain = "' . $CFG['cookie_domain'] . '";';
		$data .= 'var CKPath = "' . $CFG['cookie_path'] . '";';
		$data .= 'var CKPrex = "' . $CFG['cookie_pre'] . '";';
		File::put(DT_ROOT . '/file/script/config.js', $data);
		/* old
		$data = '
			var ixdcw = ixdcw || {};
			ixdcw.config = {
				"cookieDomain" : "'.DT_DOMAIN.'",
				"cookiePath" : "'.$CFG["cookie_path"].'",
				"cookiePre" : "'.$CFG["cookie_pre"].'"
			};
			ixdcw.lang = "'.DT_LANG.'";
			ixdcw.domain = {
				"www" : "'.SITE_URL.'",
				"img0" : "'.U::domain(U::DOMAIN_IMG0).'",
				"img1" : "'.U::domain(U::DOMAIN_IMG1).'",
			};
			ixdcw.url = {
				"ajaxUpload" : ixdcw.domain.www+"static/upload/clear.php",
				"ajaxWww" : ixdcw.domain.www+"ajax.php",
				"www":ixdcw.domain.www,
				"skin":ixdcw.domain.static+"css/"
			};';
		*/
		$data = 'var lemon = lemon || {};
			lemon.cookie = {
				domain : "'.DT_DOMAIN.'",
				path   : "'.$CFG["cookie_path"].'",
				prefix : "'.$CFG["cookie_pre"].'"
			};
			lemon.site_url = "'.SITE_URL.'";
			lemon.seajsBase = "'.PUBLIC_URL.'Js/";';
		File::put(DT_ROOT.'/Public/Js/global.js', preg_replace('/[\t\r\n\r]/','', $data));
		return true;
	}

	/**
	 * 会员组类别缓存
	 */
	public static function sysGroup() {
		global $db;
		$table  = Table::name(Table::NAME_MEMBER_GROUP);
		$data   = $group = array();
		$result = $db->query("SELECT * FROM {$table} ORDER BY listorder ASC,groupid ASC");
		while ($r = $db->fetchArray($result)) {
			$groupid        = $r['groupid'];
			$tmp            = get_setting('group-' . $groupid);
			$r['reg']       = $tmp['reg'];
			$data[$groupid] = $r;
			if ($tmp) {
				foreach ($tmp as $k => $v) {
					isset($r[$k]) or $r[$k] = $v;
				}
			}
			$r['groupid'] = $groupid;
			self::write('group-' . $groupid . '.php', $r);
		}
		self::write('group.php', $data);
	}

	/**
	 * @author   sameal
	 * @tutorial 会员级别排序缓存
	 */
   public static function sysGrouporder() {
		$group = array();
		global $db;
		$result = $db->query("SELECT groupid,memtype,memlevel FROM xd_member_group ORDER BY memlevel ASC");
		while ($r = $db->fetchArray($result)) {
			$group['DESC'] .= $r['groupid'] . ',';
			$group['ASC'] .= $r['groupid'] . ',';
			if ($r['memtype'] >= 5) {
				$group['qiye'] = $group['qiye'] . $r['groupid'] . ',';
			}
			if ($r['memtype'] == 6) {
				$group['type6'] = $group['type6'] . $r['groupid'] . ',';
			}
			if ($r['memtype'] == 7) {
				$group['type7'] = $group['type7'] . $r['groupid'] . ',';
			}
			if ($r['memtype'] == 8) {
				$group['type8'] = $group['type8'] . $r['groupid'] . ',';
			}
			if ($r['memlevel'] == 1) {
				$group['level1'] = $group['level1'] . $r['groupid'] . ',';
			}
			if ($r['memlevel'] == 2) {
				$group['level2'] = $group['level2'] . $r['groupid'] . ',';
			}
			if ($r['memlevel'] == 3) {
				$group['level3'] = $group['level3'] . $r['groupid'] . ',';
			}
		}
		$group['DESC']   = "locate(groupid,'" . trim($group['DESC'], ',') . "') DESC";
		$group['ASC']    = "locate(groupid,'" . trim($group['ASC'], ',') . "') ASC";
		$group['type6']  = trim($group['type6'], ',');
		$group['type7']  = trim($group['type7'], ',');
		$group['type8']  = trim($group['type8'], ',');
		$group['qiye']   = trim($group['qiye'], ',');
		$group['level1'] = trim($group['level1'], ',');
		$group['level2'] = trim($group['level2'], ',');
		$group['level3'] = trim($group['level3'], ',');
	    $data = "<?php defined('IN_IXDCW') or exit('Access Denied'); return " . '$group=array("DESC"=>"' . $group[DESC] . '","ASC"=>"' . $group[ASC] . '","type6"=>"' . $group['type6'] . '","type7"=>"' . $group['type7'] . '","type8"=>"' . $group['type8'] . '","qiye"=>"' . $group['qiye'] . '","level1"=>"' . $group['level1'] . '","level2"=>"' . $group['level2'] . '","level3"=>"' . $group['level3'] . '"' . ')' . "?>";
	   self::write('grouporder.php', $data);
	}

	/**
	 * 缓存类型 type函数
	 * @param string $item
	 * @return array
	 */
	public static function sysType($item = '') {
		global $db;
		$table = Table::name(Table::NAME_TYPE);
		if ($item) {
			$types  = array();
			$result = $db->query("SELECT typeid,typename,style FROM {$table} WHERE item='$item' AND cache=1 ORDER BY listorder ASC,typeid DESC");
			while ($r = $db->fetchArray($result)) {
				$types[$r['typeid']] = $r;
			}
			self::write('type-' . $item . '.php', $types);
			return $types;
		} else {
			$arr    = array();
			$result = $db->query("SELECT item FROM {$table} WHERE item!='' AND cache=1 ORDER BY typeid DESC");
			while ($r = $db->fetchArray($result)) {
				if (!in_array($r['item'], $arr)) {
					$arr[] = $r['item'];
					self::sysType($r['item']);
				}
			}
		}
	}

	/**
	 * 缓存关键链接
	 * @param string $item
	 * @return array
	 */
	public static function sysKeylink($item = '') {
		global $db;
		$table = Table::name(Table::NAME_KEYLINK);
		if ($item) {
			$keylinks = array();
			$result   = $db->query("SELECT title,url FROM {$table} WHERE item='$item' ORDER BY listorder DESC,itemid DESC");
			while ($r = $db->fetchArray($result)) {
				$keylinks[] = $r;
			}
			self::write('keylink-' . $item . '.php', $keylinks);
			return $keylinks;
		} else {
			$arr    = array();
			$result = $db->query("SELECT item FROM {$table}");
			while ($r = $db->fetchArray($result)) {
				if (!in_array($r['item'], $arr)) {
					$arr[] = $r['item'];
					self::sysKeylink($r['item']);
				}
			}
		}
	}


	/**
	 * 支付账号缓存pay.php
	 */
	public static function sysPay() {
		global $db;
		$table   = Table::name(Table::NAME_SETTING);
		$setting = $order = $pay = array();
		$result  = $db->query("SELECT * FROM {$table} WHERE item LIKE '%pay-%'");
		while ($r = $db->fetchArray($result)) {
			if (substr($r['item'], 0, 4) == 'pay-') {
				$setting[substr($r['item'], 4)][$r['item_key']] = $r['item_value'];
				if ($r['item_key'] == 'order') $order[substr($r['item'], 4)] = $r['item_value'];
			}
		}
		asort($order);
		foreach ($order as $k => $v) {
			$pay[$k] = $setting[$k];
		}
		self::write('pay.php', $pay);
	}

	/**
	 * 缓存禁止IP
	 */
	public static function sysBanip() {
		global $db, $DT_TIME;
		$table  = Table::name(Table::NAME_BANIP);
		$data   = array();
		$result = $db->query("SELECT ip,totime FROM {$table} ORDER BY itemid DESC");
		while ($r = $db->fetchArray($result)) {
			if ($r['totime'] && $r['totime'] < $DT_TIME) continue;
			$data[] = $r;
		}
		self::write('banip.php', $data);
	}


	/**
	 * 缓存用户权限
	 * @param $userid
	 */
    public static function sysRight($userid) {
	    require DT_ROOT.'/admin/admin.class.php';
	    $admin = new admin;
		$rights = $admin->get_right($userid);
		$right = $moduleids = array();
		foreach($rights as $v) {//get moduleids
			isset($moduleids[$v['moduleid']]) or $moduleids[$v['moduleid']] = $v['moduleid'];
		}
		foreach($moduleids as $m) {//get rights
			foreach($rights as $r) {
				if($r['moduleid'] == $m) {
					$r['file'] = $r['file'] ? $r['file'] : 'NA';
					$right[$m][$r['file']]['action'] = $r['action'] ? explode('|', $r['action']) : '';
					$right[$m][$r['file']]['catid'] = $r['catid'] ? explode('|', $r['catid']) : '';
				}
			}
		}
		foreach($right as $k=>$v) {
			if(isset($v['NA'])) $right[$k] = '';
		}
		foreach($right as $k=>$v) {
			if($v) {
				foreach($v as $i=>$j) {
					if(!$j['action'] && !$j['catid']) $right[$k][$i] = '';
				}
			}
		}
		self::write('right-'.$userid.'.php', $right);
	}

	/**
	 * 缓存菜单
	 * @param $userid
	 */
    public static function sysMenu($userid) {
	    require DT_ROOT.'/admin/admin.class.php';
	    $admin = new admin;
		$menus = $admin->get_menu($userid);
		$menu = $r = array();
		foreach($menus as $k=>$v) {
			$r['title'] = $v['title'];
			$r['style'] = $v['style'];
			$r['url'] = $v['url'];
			$menu[] = $r;
		}
		self::write('menu-'.$userid.'.php', $menu);
	}


	/**
	 * 缓存禁止的关键词
	 */
	public static function sysBanword() {
		global $db;
		$table  = Table::name(Table::NAME_BANWORD);
		$data   = array();
		$result = $db->query("SELECT * FROM {$table} ORDER BY bid DESC");
		while ($r = $db->fetchArray($result)) {
			$b      = array();
			$b[]    = $r['replacefrom'];
			$b[]    = $r['replaceto'];
			$b[]    = $r['deny'];
			$data[] = $b;
		}
		self::write('banword.php', $data);
	}

	/**
	 * 缓存禁止评论的模块
	 * @param int $moduleid
	 * @return array
	 */
	public static function sysBancomment($moduleid = 0) {
		global $db, $MODULE;
		$table = Table::name(Table::NAME_COMMENT_BAN);
		if ($moduleid) {
			$data   = array();
			$result = $db->query("SELECT itemid FROM {$table} WHERE moduleid='$moduleid' ORDER BY bid DESC ");
			while ($r = $db->fetchArray($result)) {
				$data[] = $r['itemid'];
			}
			self::write('bancomment-' . $moduleid . '.php', $data);
			return $data;
		} else {
			foreach ($MODULE as $k => $v) {
				if ($k < 4 || $v['islink']) continue;
				self::sysBancomment($k);
			}
		}
	}

	public static function sysAll() {
		self::sysModule();
		self::sysArea();
		self::sysCategory();
		self::sysFields();
		self::sysGroup();
		self::sysPay();
		self::sysType();
		self::sysKeylink();
		self::sysOauth();
		return true;
	}

	/**
	 * 通讯工具占帐号oauth.php
	 */
	public static function sysOauth() {
		global $db;
		$table   = Table::name(Table::NAME_SETTING);
		$setting = $order = $oauth = array();
		$result  = $db->query("SELECT * FROM {$table} WHERE item LIKE '%oauth-%'");
		while ($r = $db->fetchArray($result)) {
			if (substr($r['item'], 0, 6) == 'oauth-') {
				$setting[substr($r['item'], 6)][$r['item_key']] = $r['item_value'];
				if ($r['item_key'] == 'order') $order[substr($r['item'], 6)] = $r['item_value'];
			}
		}
		asort($order);
		foreach ($order as $k => $v) {
			$oauth[$k] = $setting[$k];
		}
		self::write('oauth.php', $oauth);
	}

	/**
	 * 清空sql缓存
	 * @param      $dir
	 * @param bool $all
	 */
	public static function sysClearSql($dir, $all = false) {
		global $DT_TIME;
		if ($dir) {
			$globs = glob(DT_CACHE . '/sql/' . $dir . '/*.php');
			if ($globs) {
				foreach ($globs as $v) {
					if ($all) {
						File::del($v);
					} else {
						$exptime = intval(substr(File::get($v), 8, 18));
						if ($exptime && $DT_TIME > $exptime) File::del($v);
					}
				}
			}
		} else {
			self::clear('php', 'dir', 'sql');
		}
	}

}